package com.thinker.interview.dynamic_datasource.dynamic_datasource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DynamicDataSourceConfig {

    @Bean(name = "cnDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.cn")
    public DataSource cnDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sgDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.sg")
    public DataSource sgDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource dynamicDataSource() {
        Map<Object, Object> dataSourceMap = new HashMap<>(2);
        dataSourceMap.put("CN", cnDataSource());
        dataSourceMap.put("SG", sgDataSource());
        DynamicDatasource dynamicDatasource = new DynamicDatasource();
        dynamicDatasource.setTargetDataSources(dataSourceMap);
        dynamicDatasource.setDefaultTargetDataSource(cnDataSource());
        return dynamicDatasource;
    }
}
